//
//  BankCardUpdateVC.swift
//  kxf
//
//  Created by Mac on 2024/3/9.
//

import Foundation
import UIKit
import MCToast

class BankCardUpdateVC: WHBaseViewVC {
    
    var bankcardpic = ""
    var bankBranchNo = ""
    var bankBranchName = ""
    
    var imgType = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
    }
    lazy var titleVm : RegisterViewHeadTitleVM = {
        let vm = RegisterViewHeadTitleVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: 0, height: 0))
        vm.titleLabel.text = "结算卡信息"
        return vm
    }()
    
    lazy var nameVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: self.titleVm.frame.maxY, width: 0, height: 0))
        vm.leftLabel.text = "姓名"
        vm.textField.isEnabled = false
        vm.textField.text = UserModel.shared.agentName
//        vm.textField.placeholder = "请输入"
//        vm.textField.keyboardType = .default
//        vm.maxLength =
        return vm
    }()
    lazy var phoneVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: self.nameVm.frame.maxY, width: 0, height: 0))
        vm.leftLabel.text = "手机号"
        vm.textField.placeholder = "请输入"
        vm.textField.keyboardType = .numberPad
        vm.maxLength = 11
        return vm
    }()
    lazy var bankCardNoVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: self.phoneVm.frame.maxY, width: 0, height: 0))
        vm.leftLabel.text = "卡号"
        vm.textField.placeholder = "请输入银行卡号"
        vm.textField.keyboardType = .numberPad
        vm.maxLength = 30
        return vm
    }()
    lazy var bankBranchVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: self.bankCardNoVm.frame.maxY, width: 0, height: 0))
        vm.leftLabel.text = "开户支行"
        vm.textField.placeholder = "请选择开户支行"
        vm.showArrowImg()
        vm.tapBlock = {()in
            let vc = AuthenBankBranchListVC()
            vc.tapBlock = {(dict)in
                self.bankBranchNo = "\(dict["branchNo"]as? String ?? "")"
                self.bankBranchName = "\(dict["branchBankName"]as? String ?? "")"
                self.bankBranchVm.setLabelContent(content: self.bankBranchName)
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        return vm
    }()
    lazy var photoWhiteView : UIView = {
        let vi = UIView.init(frame: CGRect.init(x: 0, y: self.bankBranchVm.frame.maxY + kFitWidth(10), width: SCREEN_WIDHT, height:AuthenPhotoVM().selfHeight+kFitWidth(20)))
        vi.backgroundColor = .white
        vi.isUserInteractionEnabled = true
        
        return vi
    }()
    lazy var bankCardPhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: SCREEN_WIDHT*0.25, y: kFitWidth(10), width: 0, height: 0  ))
        vm.titleLabel.text = "银行卡卡号照"
        vm.photoBlock = {()in
            self.imgType = "bankCardFront"
            self.takePickture()
        }
        
        vm.exampleBlock = {()in
            self.sampleAlertVm.showExampleImage(type: .bankFront)
        }
        return vm
    }()
    lazy var confirmBtn : UIButton = {
        let btn = UIButton()
        btn.frame = CGRect.init(x: kFitWidth(31), y: self.photoWhiteView.frame.maxY+kFitWidth(40), width: kFitWidth(316), height: kFitWidth(48))
        btn.setTitle("确定", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "button_theme_bg"), for: .normal)
        btn.layer.cornerRadius = kFitWidth(24)
        btn.clipsToBounds = true
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        btn.backgroundColor = .clear
        
        btn.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var sampleAlertVm : AuthenPhotoSampleAlertVM = {
        let vm = AuthenPhotoSampleAlertVM.init(frame: .zero)
        vm.isHidden = true
        return vm
    }()
}

extension BankCardUpdateVC{
    @objc func submitAction() {
        if !judgePhoneNumber(phoneNum: phoneVm.textField.text){
            MCToast.mc_text("请输入正确的手机号码")
            return
        }
        if bankCardNoVm.textField.text?.count ?? 0 < 6 {
            MCToast.mc_text("请输入银行卡号")
            return
        }
        if bankcardpic.count < 5 {
            MCToast.mc_text("去上传银行卡卡号照")
            return
        }
        if bankBranchNo.count < 2 {
            MCToast.mc_text("请选择开户支行")
            return
        }
        sendUpdateBankRequest()
    }
}

extension BankCardUpdateVC{
    func initUI() {
        initNavi(titleStr: "结算卡更改")
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        view.addSubview(titleVm)
        view.addSubview(nameVm)
        view.addSubview(phoneVm)
        view.addSubview(bankCardNoVm)
        view.addSubview(bankBranchVm)
        
        view.addSubview(photoWhiteView)
        photoWhiteView.addSubview(bankCardPhotoVm)
        
        UIApplication.shared.keyWindow?.addSubview(sampleAlertVm)
        
        view.addSubview(confirmBtn)
    }
}

extension BankCardUpdateVC:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    @objc func takePickture(){
        let alertController=UIAlertController(title: "请选择照片来源", message: nil, preferredStyle: .actionSheet)

        let cancel=UIAlertAction(title:"取消", style: .cancel, handler: nil)
        
        let takingPictures=UIAlertAction(title:"拍照", style: .default){ action in
            if UIImagePickerController.isSourceTypeAvailable(.camera){
                let vc = DXIDCardCameraController.init(type: DXIDCardType.bank)
                vc.delegate = self
                vc.modalPresentationStyle = .fullScreen
                self.present(vc, animated: true, completion: nil)
            } else {
                print("不支持拍照")
            }
        }
        let photoPictures=UIAlertAction(title:"相册", style: .default){ action in
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = true
                cameraPicker.sourceType = .photoLibrary
                //在需要的地方present出来
                self.present(cameraPicker, animated: true, completion: nil)
            } else {
                print("不支持拍照")
            }
        }
        
        alertController.addAction(cancel)
        alertController.addAction(takingPictures)
        alertController.addAction(photoPictures)
        
        self.present(alertController, animated:true, completion:nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        print("获得照片============= \(info)")
        self.dismiss(animated: true, completion: nil)
        MCToast.mc_loading()
        let image = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage)!
        let imageData = WHRequestTools.compressImage(toData: image)
//        let imageData = image.jpegData(compressionQuality: 1.0)
        
        DSImageUploader.shared.uploadImages(_image: imageData!,imgType: "\(self.imgType)") { text, value in
            DLLog(message: "\(text)")
            DLLog(message: "\(value)")
            MCToast.mc_remove()
            if value == true{
                self.sendOcrBankCardRequest(urlString: "\(text)")
            }else{
                MCToast.mc_text("图片上传失败")
            }
        }
    }
}


extension BankCardUpdateVC : DXIDCardCameraControllerProtocol {
    func cameraDidFinishShootWithCameraImage(image: UIImage) {
        let imageData = WHRequestTools.compressImage(toData: image)
//        let imageData = image.jpegData(compressionQuality: 1.0)
        MCToast.mc_loading()
        DSImageUploader.shared.uploadImages(_image: imageData!,imgType: "\(self.imgType)") { text, value in
            DLLog(message: "\(text)")
            DLLog(message: "\(value)")
            MCToast.mc_remove()
            if value == true{
                self.sendOcrBankCardRequest(urlString: "\(text)")
            }else{
                MCToast.mc_text("图片上传失败")
            }
        }
    }
}
extension BankCardUpdateVC{
    func sendOcrBankCardRequest(urlString:String) {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_OCR_bank)?url=\(urlString)", vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            if responseObject["code"]as? Int ?? 0 == 200{
                let dict = responseObject["data"]as? NSDictionary ?? [:]
                let result = dict["result"]as? NSDictionary ?? [:]
                let bankMsg = result["result"]as? NSDictionary ?? [:]
                self.bankCardPhotoVm.setImgUrl(urlstring: urlString)
                self.bankcardpic = urlString
                
                let bankNo = bankMsg["bank_card_number"]as? String ?? ""
//                let bankStr = bankNo.trimmingCharacters(in: .whitespacesAndNewlines)
                let bankStr = bankNo.replacingOccurrences(of: " ", with: "")
                self.bankCardNoVm.textField.text = bankStr
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "识别失败，请重新拍摄照片")", viewController: self)
            }
        }
    }
    func sendUpdateBankRequest() {
        MCToast.mc_loading()
        var urlString = "\(URL_bank_update)?bankcardpic=\(bankcardpic)&bankCard=\(bankCardNoVm.textField.text ?? "")&bankPhone=\(phoneVm.textField.text ?? "")&bankBranchName=\(bankBranchName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")&bankBranchNo=\(bankBranchNo)"
        urlString = urlString.replacingOccurrences(of: " ", with: "")
        
        WHNetworkUtil.shareManager().GET(urlString: urlString) { responseObject in
            if responseObject["code"]as? Int ?? -1 == 200{
                self.presentAlertVc(confirmBtn: "确定", message: "", title: "银行卡修改成功", cancelBtn: nil, handler: { action in
                    self.backTapAction()
                }, viewController: self)
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "银行卡修改失败")", viewController: self)
            }
        }
    }
}
